<template>
	<view class="container">
		<view class="main">
			<!-- 头部 -->
			<view class="nav">
				<view class="header">
					<!-- 未接单 	如果是自取 ，默认自取 显示商家距离  -->
					<view class="left" v-if="orderType == 'takein'">
						<view class="store-name">
							<text>{{ store.name }}</text>
							<view class="iconfont iconarrow-right"></view>
						</view>
						<view class="store-location">
							<image src='/static/images/order/location.png' style="width: 30rpx; height: 30rpx;"
								class="mr-10"></image>
							<text>距离您 {{ store.distance_text}} 米</text>
						</view>
					</view>
					<!-- 如果是外卖 ，显示街道 -->
					<view class="left overflow-hidden" v-else>
						<view class="d-flex align-items-center overflow-hidden">
							<image src='/static/images/order/location.png' style="width: 30rpx; height: 30rpx;"
								class="mr-10"></image>
							<view class="font-size-extra-lg text-color-base font-weight-bold text-truncate">
								{{ address.street }}
							</view>
						</view>
						<view class="font-size-sm text-color-assist overflow-hidden text-truncate">
							由<text class="text-color-base" style="margin: 0 10rpx">{{ store.name }}</text>配送
						</view>
					</view>
					<!-- 已接单  点击后样式变化 -->
					<view class="right">
						<view class="dinein" :class="{active: orderType == 'takein'}" @tap="SET_ORDER_TYPE('takein')">
							<text>自取</text>
						</view>
						<view class="takeout" :class="{active: orderType == 'takeout'}" @tap="takout">
							<text>外卖</text>
						</view>
					</view>
				</view>
				<view class="coupon">
					<text class="title">"霸气mini卡"超级购券活动，赶紧去购买</text>
					<view class="iconfont iconarrow-right"></view>
				</view>
			</view>
			<!-- 中间左侧 -->
			<view class="content">
				<scroll-view class="menus" scroll-with-animation scroll-y>
					<view class="wrapper">
						<view class="menu" :id="`menu-${item.id}`" :class="{'current': item.id === currentCateId}"
							@tap="handleMenuTap(item.id)" v-for="(item, index) in goods" :key="index">
							<text>{{ item.name }}</text>
							<!-- 加入购物车后 -->
							<view class="dot" v-show="menuCartNum(item.id)">{{ menuCartNum(item.id) }}</view>
						</view>
					</view>
				</scroll-view>
				<!-- 中间右侧 -->
				<scroll-view class="goods" scroll-with-animation scroll-y :scroll-top="cateScrollTop"
					@scroll="handleGoodsScroll">
					<view class="wrapper">
						<!-- 轮播图 -->
						<swiper class="ads" id="ads" autoplay :interval="3000" indicator-dots>
							<swiper-item v-for="(item, index) in ads" :key='index'>
								<image :src="item.image"></image>
							</swiper-item>
						</swiper>
						<!-- 商品列表 -->
						<view class="list">
							<!-- category begin -->
							<view class="category" v-for="(item, index) in goods" :key="index" :id="`cate-${item.id}`">
								<!-- 大标题  系列 -->
								<view class="title">
									<text>{{ item.name }}</text>
									<image :src="item.icon" class="icon"></image>
								</view>
								<view class="items">
									<!-- 每一个商品 begin -->
									<view class="good" v-for="(good, key) in item.goods_list" :key="key">
										<image :src="good.images" class="image" @tap="showGoodDetailModal(item, good)">
										</image>
										<view class="right">
											<text class="name">{{ good.name }}</text>
											<text class="tips">{{ good.content }}</text>
											<view class="price_and_action">
												<text class="price">￥{{ good.price }}</text>
												<!-- 选规格 use_property 1  -->
												<view class="btn-group" v-if="good.use_property">
													<button type="primary" class="btn property_btn" hover-class="none"
														size="mini" @tap="showGoodDetailModal(item, good)">
														选规格
													</button>
													<view class="dot" v-show="goodCartNum(good.id)">
														{{ goodCartNum(good.id) }}</view>
												</view>
												<!-- 无选规格 use_property 0  正常增减数量-->
												<view class="btn-group" v-else>
													<!-- 减少 -->
													<button type="default" plain class="btn reduce_btn" size="mini"
														hover-class="none" v-show="goodCartNum(good.id)"
														@tap="handleReduceFromCart(item, good)">
														<view class="iconfont iconsami-select"></view>
													</button>
													<view class="number" v-show="goodCartNum(good.id)">
														{{ goodCartNum(good.id) }}
													</view>
													<!-- 增加 -->
													<button type="primary" class="btn add_btn" size="min"
														hover-class="none" @tap="handleAddToCart(item, good, 1)">
														<view class="iconfont iconadd-select"></view>
													</button>
												</view>
											</view>
										</view>
									</view>
									<!-- 商品 end -->
								</view>
							</view>
							<!-- category end -->
						</view>
					</view>
				</scroll-view>
			</view>
			<!-- 购物车栏 begin -->
			<view class="cart-box" v-if="cart.length > 0">
				<view class="mark">
					<image src="/static/images/menu/cart.png" class="cart-img" @tap="openCartPopup"></image>
					<view class="tag">{{ getCartGoodsNumber }}</view>
				</view>
				<view class="price">￥{{ getCartGoodsPrice }}</view>
				<button type="primary" class="pay-btn" @tap="toPay" :disabled="disabledPay">
					{{ disabledPay ? `差${spread}元起送` : '去结算' }}
				</button>
			</view>
			<!-- 购物车栏 end -->
		</view>
		<!-- 商品详情模态框 begin -->
		<modal :show="goodDetailModalVisible" class="good-detail-modal" color="#5A5B5C" width="90%" custom
			padding="0rpx" radius="12rpx">
			<!-- 上方介绍 -->
			<view class="cover">
				<image v-if="good.images" :src="good.images" class="image"></image>
				<view class="btn-group">
					<image src="/static/images/menu/share-good.png"></image>
					<image src="/static/images/menu/close.png" @tap="closeGoodDetailModal"></image>
				</view>
			</view>
			<scroll-view class="detail" scroll-y>
				<view class="wrapper">
					<!-- 商品名称 -->
					<view class="basic">
						<view class="name">{{ good.name }}</view>
						<view class="tips">{{ good.content }}</view>
					</view>
					<!--  选规格 种类-->
					<view class="properties" v-if="good.use_property">
						<view class="property" v-for="(item, index) in good.property" :key="index">
							<!-- 标题 -->
							<view class="title">
								<text class="name">{{ item.name }}</text>
								<view class="desc" v-if="item.desc">({{ item.desc }})</view>
							</view>
							<!--选规格 内容 -->
							<view class="values">
								<view class="value" v-for="(value, key) in item.values" :key="key"
									:class="{'default': value.is_default}" @tap="changePropertyDefault(index, key)">
									{{ value.value }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="action">
				<!-- 左侧金额 -->
				<view class="left">
					<view class="price">￥{{ good.price }}</view>
					<!-- 选规格的详细信息 -->
					<view class="props" v-if="getGoodSelectedProps(good)">
						{{ getGoodSelectedProps(good) }}
					</view>
				</view>
				<!-- 右侧 选择数量 -->
				<view class="btn-group">
					<button type="default" plain class="btn" size="mini" hover-class="none" @tap="handlePropertyReduce">
						<view class="iconfont iconsami-select"></view>
					</button>
					<view class="number">{{ good.number }}</view>
					<button type="primary" class="btn" size="min" hover-class="none" @tap="handlePropertyAdd">
						<view class="iconfont iconadd-select"></view>
					</button>
				</view>
			</view>
			<!-- 下方 加入购物车 按钮 -->
			<view class="add-to-cart-btn" @tap="handleAddToCartInModal">
				<view>加入购物车</view>
			</view>
		</modal>
		<!-- 商品详情模态框 end -->
		<!-- 购物车详情popup begin-->
		<popup-layer direction="top" :show-pop="cartPopupVisible" class="cart-popup">
			<template slot="content">
				<view class="top">
					<text @tap="handleCartClear">清空</text>
				</view>
				<scroll-view class="cart-list" scroll-y>
					<view class="wrapper">
						<!-- 购物车列表 -->
						<view class="item" v-for="(item, index) in cart" :key="index">
							<view class="left">
								<view class="name">{{ item.name }}</view>
								<view class="props">{{ item.props_text }}</view>
							</view>
							<view class="center">
								<text>￥{{ item.price }}</text>
							</view>
							<view class="right">
								<button type="default" plain size="mini" class="btn" hover-class="none"
									@tap="handleCartItemReduce(index)">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">{{ item.number }}</view>
								<button type="primary" class="btn" size="min" hover-class="none"
									@tap="handleCartItemAdd(index)">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
						<!-- 外卖 包装费 -->
						<view class="item" v-if="orderType == 'takeout' && store.packing_fee">
							<view class="left">
								<view class="name">包装费</view>
							</view>
							<view class="center">
								<text>￥{{ parseFloat(store.packing_fee) }}</text>
							</view>
							<view class="right invisible">
								<button type="default" plain size="mini" class="btn" hover-class="none">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">1</view>
								<button type="primary" class="btn" size="min" hover-class="none">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
					</view>
				</scroll-view>
			</template>
		</popup-layer>
		<!-- 购物车详情popup end-->
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapGetters,
		mapMutations
	} from 'vuex'
	import modal from '@/components/modal/modal'
	import popupLayer from '@/components/popup-layer/popup-layer'
	export default {
		components: {
			modal
		},
		data() {
			return {
				goods: [], //所有商品
				currentCateId: 6905, //默认分类
				cateScrollTop: 0, //scroll-view滑动刻度
				goodDetailModalVisible: false, //是否饮品详情模态框
				good: {}, //当前饮品
				cart: [], //购物车
				category: {}, //当前饮品所在分类
				cartPopupVisible: false,//购物栏popup是否显示
				ads: [{
						image: 'https://s3.uuu.ovh/imgs/2024/12/26/93968f66a1838191.png'
					},
					{
						image: 'https://s3.uuu.ovh/imgs/2024/12/26/1aa2d8b3ff40315a.png'
					},
					{
						image: 'https://s3.uuu.ovh/imgs/2024/12/26/35ea26b9f691d977.png'
					},
					{
						image: 'https://s3.uuu.ovh/imgs/2024/12/26/a391d87d1661cbc2.jpg'
					},
					{
						image: 'https://s3.uuu.ovh/imgs/2024/12/26/6fbf2d2a5e8be9d0.jpg'
					}
				], //轮播图数据
			}
		},
		computed: {
			...mapState(['orderType', 'store', 'address']), //引用数据
			...mapGetters(['isLogin']),
			goodCartNum() { //计算单个饮品添加到购物车的数量
				return (id) => this.cart.reduce((acc, cur) => { // (acc) (累加器)   (cur) (当前元素的值)
					if (cur.id === id) { //通过id到购物车中找到此商品
						return acc += cur.number //计算
					}
					return acc
				}, 0)
			},
			getCartGoodsNumber() { //计算购物车总数
				return this.cart.reduce((acc, cur) => acc + cur.number, 0)
			},
			getCartGoodsPrice() { //计算购物车总价
				return this.cart.reduce((acc, cur) => acc + cur.number * cur.price, 0)
			},
			disabledPay() { //是否达到起送价
				return this.orderType == 'takeout' && (this.getCartGoodsPrice < this.store.min_price) ? true : false
			},
			spread() { //差多少元起送
				if (this.orderType != 'takeout') return
				return parseFloat((this.store.min_price - this.getCartGoodsPrice).toFixed(2))
			},
			menuCartNum() { //每一栏的数量，进行判断赛选
				return (id) => this.cart.reduce((acc, cur) => {
					if (cur.cate_id === id) {
						return acc += cur.number
					}
					return acc
				}, 0)
			},
		},
		async onLoad() {
			await this.init() //在生命周期调用初始化页面
		},
		methods: {
			...mapMutations(['SET_ORDER_TYPE']), //点击自取，设置order_type的参数
			...mapActions(['getStore']), //引入getStore方法
			async init() { //页面初始化方法
				await this.getStore() //调用getStore方法，对store变量进行商家数据填充
				this.goods = await this.$api('goods') //对goods变量进行货物数据填充
			},
			takout() { //点击外卖
				if (this.orderType == 'takeout') return //如果是选取外卖状态，则返回
				if (!this.isLogin) { //未登录
					uni.navigateTo({
						url: '/pages/login/login'
					})
					return
				}
				uni.navigateTo({ //跳转地址页面
					url: '/pages/address/address'
				})
			},
			handleGoodsScroll({
				detail
			}) { //商品列表滚动事件
				if (!this.sizeCalcState) {
					this.calcSize() //为每个item添加一个top高度
				}
				const {
					scrollTop
				} = detail //detail为参数，可以查看scrollTop，根据scrollTop来联动左侧item
				let tabs = this.goods.filter(item => item.top <= scrollTop).reverse() //过滤、排序，
				if (tabs.length > 0) {
					this.currentCateId = tabs[0].id //定义currentCateId 如果跟item.id一样，则使用:class
				}
			},
			calcSize() {
				let h = 10
				//该方法位获取轮播图的高度
				let view = uni.createSelectorQuery().select('#ads') //获取轮播图节点
				view.fields({
					size: true
				}, data => {
					h += Math.floor(data.height) //赋予h参数轮播图高度
				}).exec()
				//获取每个item的高度，叠加，装入数据里面
				this.goods.forEach(item => {
					let view = uni.createSelectorQuery().select(`#cate-${item.id}`) //每个商品view
					view.fields({
						size: true
					}, data => {
						item.top = h //为每个item设置一个top属性
						h += data.height //对h属性增加一个item高度
						item.bottom = h //设置item的底部bottom属性
					}).exec()
				})
				this.sizeCalcState = true
			},
			handleMenuTap(id) { //点击菜单项事件
				if (!this.sizeCalcState) {
					this.calcSize() //为每个item添加一个top高度
				}
				this.currentCateId = id
				this.$nextTick(() => this.cateScrollTop = this.goods.find(item => item.id == id).top) //
			},
			showGoodDetailModal(item, good) { //打开商品详情
				this.good = JSON.parse(JSON.stringify({
					...good,
					number: 1
				})) //当前饮品赋予good值，多加一个属性number
				this.goodDetailModalVisible = true
				this.category = JSON.parse(JSON.stringify(item)) //当前饮品所在种类赋值
			},
			closeGoodDetailModal() { //关闭饮品详情模态框
				this.goodDetailModalVisible = false
				this.good = {} //清空
				this.category = {}
			},
			getGoodSelectedProps(good, type = 'text') { //计算当前饮品所选属性 文字
				if (good.use_property) {
					let props = []
					good.property.forEach(({
						values
					}) => {
						values.forEach(value => {
							if (value.is_default) {
								props.push(type === 'text' ? value.value : value.id)
							}
						})
					})
					return type === 'text' ? props.join('，') : props
				}
				return ''
			},
			changePropertyDefault(index, key) { //改变默认属性值
				this.good.property[index].values.forEach(value => this.$set(value, 'is_default', 0)) //遍历每个is_default值为0
				this.good.property[index].values[key].is_default = 1 //点击后 改为 1 做状态调整
				this.good.number = 1 //点击后该商品数量为1
			},
			handleAddToCart(cate, good, num) { //添加到购物车 +1
				const index = this.cart.findIndex(item => { //findIndex() 方法返回传入一个条件（函数）符合条件的数组第一个元素位置,如果没有符合条件的元素返回 -1
					if (good.use_property) { //如果是选规格的
						return (item.id === good.id) && (item.props_text === good.props_text)
					} else {
						return item.id === good.id
					}
				})
				if (index > -1) {
					this.cart[index].number += num //如果对象已有，直接在已有的对象上加1
				} else {
					this.cart.push({ //否则 重新添加进购物车 
						id: good.id,
						cate_id: cate.id,
						name: good.name,
						price: good.price,
						number: num,
						image: good.images,
						use_property: good.use_property,
						props_text: good.props_text,
						props: good.props
					})
				}
			},
			handleReduceFromCart(item, good) { //减少商品 -1
				const index = this.cart.findIndex(item => item.id === good.id)
				this.cart[index].number -= 1
				if (this.cart[index].number <= 0) {
					this.cart.splice(index, 1) //如果减少到了0，则剔除该商品
				}
			},
			handlePropertyAdd() { //加一个商品
				this.good.number += 1
			},
			handlePropertyReduce() { //减一个商品
				if (this.good.number === 1) return
				this.good.number -= 1
			},
			handleAddToCartInModal() { //加入购物车
				const product = Object.assign({}, this.good, {
					props_text: this.getGoodSelectedProps(this.good),
					props: this.getGoodSelectedProps(this.good, 'id')
				})
				this.handleAddToCart(this.category, product, this.good.number)
				this.closeGoodDetailModal()
			},
			handleCartItemAdd(index) {//购物车栏减少
				this.cart[index].number += 1
			},
			handleCartItemReduce(index) {//购物车栏增加
				if(this.cart[index].number === 1) {
					this.cart.splice(index, 1)
				} else {
					this.cart[index].number -= 1
				}
				if(!this.cart.length) {
					this.cartPopupVisible = false
				}
			},
			openCartPopup() {	//打开/关闭购物车列表popup
				this.cartPopupVisible = !this.cartPopupVisible
			},
			handleCartClear() {	//清空购物车
				uni.showModal({
					title: '提示',
					content: '确定清空购物车么',
					success: ({confirm}) =>  {
						if(confirm) {
							this.cartPopupVisible = false
							this.cart = []
						}
					}
				})
			},
			toPay() {//支付
				if (!this.isLogin) {
					uni.navigateTo({
						url: '/pages/login/login'
					})
					return
				}
				uni.showLoading({
					title: '加载中'
				})
				uni.setStorageSync('cart', JSON.parse(JSON.stringify(this.cart)))//将购物车数据存入本地数据
				uni.navigateTo({
					url: '/pages/pay/pay'
				})
				uni.hideLoading()
			}
		}
	}
</script>
<style lang="scss" scoped>
	@import '~@/pages/menu/menu.scss';
</style>